package com.yunxin.core.utils.infra.support.rabbit;

import cn.hutool.core.lang.UUID;
import com.yunxin.common.utils.JacksonUtils;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author zero°
 * @since 2024-01-02
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class RabbitSenderWithCallback {

    private final RabbitTemplate rabbitTemplate;


    @PostConstruct
    public void initRabbitTemplate() {
        // 设置生产者消息确认
        rabbitTemplate.setConfirmCallback(new RabbitConfirmCallback());
        rabbitTemplate.setReturnsCallback(new RabbitReturnCallback());
    }

    /**
     * 发送消息
     * @param exchange exchange
     * @param routingKey routingKey
     * @param messageData messageData
     */
    public void send(String exchange, String routingKey, Object messageData) {
        //1.发送一条未被路由消息
        MessageProperties messageProperties = new MessageProperties();
        String msgId = MDC.get("TRACE_ID");
        if (StringUtils.isEmpty(msgId)) {
            msgId = UUID.randomUUID().toString();
        }
        //此处设置的msgId才能被会转成rabbitmq client的messageId，发送给broker
        messageProperties.setMessageId(msgId);
        String jsonMessage = JacksonUtils.X.format(messageData);
        Message message = new Message(jsonMessage.getBytes(), messageProperties);
        rabbitTemplate.convertAndSend(exchange, routingKey, message, new CorrelationData(msgId));
        log.info("发送一条消息,exchange:{},routingKey:{},message:{}", exchange, routingKey, JacksonUtils.X.format(messageData));
    }
}
